<template>
  <div id="consultPlanDetailPage">
    <!-- 麵包屑導航 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />

    <!-- 消息詳情卡片 -->
    <a-space direction="vertical" style="width: 100%">
      <a-card title="基本參數" class="detail-card" :loading="loading">
        <template v-if="!loading && !consultPlan.id">
          <a-empty description="數據加載失敗，請重試" />
        </template>
        <template v-else>
          <a-descriptions bordered>
            <a-descriptions-item label="診金方案標題">
              {{ consultPlan.title }}
            </a-descriptions-item>
          </a-descriptions>
        </template>
      </a-card>
      <!-- 添加 -->
      <a-space>
        <a-button type="primary" @click="handleBatchSetup">
          <template #icon>
            <SettingOutlined />
          </template>
          批量設置
        </a-button>
      </a-space>

      <a-table
        :dataSource="consultPlan.consultTypes"
        :columns="consultPlanItemColumns"
        :loading="loading"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'consultType'">
            {{ record.name }}
          </template>
          <template v-if="column.dataIndex === 'shareType'">
            <a-tag color="orange" v-if="record.shareType === 1">固定金額</a-tag>
            <a-tag color="blue" v-else>比例</a-tag>
          </template>
          <template v-if="column.dataIndex === 'shareValue'">
            <template v-if="record.shareType === 1"
              >$ {{ record.shareValue }}</template
            >
            <template v-else> {{ record.shareValue }}%</template>
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleSetting(record)">設置</a-button>
          </template>
        </template>
      </a-table>
      <BackButton />
    </a-space>
    <!-- 設置 -->
    <a-modal v-model:open="showModalSetting" :footer="null">
      <template #title> 設置-{{ settingFormData.name }} </template>
      <DynamicForm
        ref="settingFormRef"
        :fieldConfig="settingFieldConfig"
        :formData="settingFormData"
        @submit="handleSettingSubmit"
      />
    </a-modal>

    <!-- 批量設置抽屜 -->
    <a-drawer
      title="批量設置"
      :width="720"
      :open="showBatchDrawer"
      @close="showBatchDrawer = false"
    >
      <template #extra>
        <a-space>
          <a-button @click="showBatchDrawer = false">取消</a-button>
          <a-button type="primary" @click="handleBatchSetupSubmit"
            >提交</a-button
          >
        </a-space>
      </template>
      <a-form ref="formRef" :model="formState">
        <a-card
          v-for="(item, index) in formState"
          :key="index"
          :title="item.name"
          size="small"
          style="margin-bottom: 8px"
          hoverable
        >
          <a-row :gutter="8">
            <a-col :span="3">
              <!-- 空 -->
            </a-col>
            <a-col :span="10">
              <a-form-item label="分成類型">
                <a-radio-group
                  v-model:value="item.shareType"
                  button-style="solid"
                  class="full-width-radio"
                >
                  <a-radio-button :value="1">固定金額</a-radio-button>
                  <a-radio-button :value="2">百分比</a-radio-button>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="佣金">
                <a-input-number
                  v-model:value="item.shareValue"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  :max="item.shareType === 2 ? 100 : null"
                  :addonBefore="item.shareType === 1 ? '$' : null"
                  :addonAfter="item.shareType === 2 ? '%' : null"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { SettingOutlined } from "@ant-design/icons-vue";
import { useRoute } from "vue-router";
import { consultPlanApi } from "@/api";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";

import { tableColumns, getSettingFieldConfig } from "@/models/consultPlanItem";
import { message } from "ant-design-vue";
import BackButton from "@/components/BackButton.vue";
import DynamicForm from "@/components/DynamicForm.vue";

const route = useRoute();

// 麵包屑導航
const breadcrumbItems = [
  { url: "/consult-plan", name: "診金方案" },
  { url: "", name: "診金方案項詳情" },
];

// 詳情數據
const consultPlan = reactive({
  id: 0,
  title: "",
  consultTypes: [],
  updatedAt: "",
  updatedBy: "",
});
const loading = ref(true);
const consultPlanId = Number(route.params.id);

// 獲取詳情
const fetchDetail = async () => {
  try {
    const { data } = await consultPlanApi.getConsultPlanDetail(consultPlanId);
    Object.assign(consultPlan, data);
  } catch (error) {
    console.error("獲取詳情失敗", error);
  } finally {
    loading.value = false;
  }
};

// 初始化加載
onMounted(() => {
  fetchDetail();
});

const consultPlanItemColumns = tableColumns;

// 單個設置
const settingFormData = reactive<any>({});
const settingFieldConfig = ref<Record<string, any>>({});
const showModalSetting = ref(false);
const settingFormRef = ref();
const settingConsultType = ref(0);

const handleSetting = (record: any) => {
  showModalSetting.value = true;
  Object.assign(settingFormData, record);
  console.log(record);
  settingConsultType.value = record.id;
  if (Object.keys(settingFieldConfig.value).length === 0) {
    settingFieldConfig.value = getSettingFieldConfig();
  }
};

const handleSettingSubmit = async (data: any) => {
  try {
    data["consultType"] = settingConsultType.value;
    await consultPlanApi.setConsultTypes(consultPlanId, { items: [data] });
    message.success("設置診金方案項成功");
    showModalSetting.value = false;
    fetchDetail();
  } catch (error) {
    console.error("設置項失敗", error);
  } finally {
    settingFormRef.value.resetLoading();
  }
};

// 批量設置
const showBatchDrawer = ref(false);
const formState = ref([]);
const formRef = ref();

// 打開批量設置抽屜
const handleBatchSetup = () => {
  showBatchDrawer.value = true;
  formState.value = consultPlan.consultTypes.map((item) => ({
    name: item.name,
    consultType: item.id,
    shareType: Number(item.shareType),
    shareValue: item.shareValue,
  }));
};

const handleBatchSetupSubmit = async () => {
  try {
    await formRef.value.validate();
    await consultPlanApi.setConsultTypes(consultPlanId, {
      items: formState.value,
    });
    message.success("批量設置診金方案項成功");
    showBatchDrawer.value = false;
    fetchDetail();
  } catch (error) {
    console.error("批量設置診金方案項失敗", error);
  }
};
</script>

<style scoped></style>
